<?php

namespace App\Http\Controllers\Admin;

use App\Theme;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ThemeController extends Controller
{
    /*
     *
     */
    public function index(Request $request){
        $searchKey=$request->searchKey;
        $searchTime=$request->searchTime;
        $category_id=$request->category_id;
        return view('admin.theme.list',compact('searchKey','searchTime','category_id'));
    }
    public function ajax_list(Request $request){

        $theme=Theme::select('id','name','category_id','created_at','updated_at');
        if($request->searchKey){
            $theme=$theme->where('name','like', '%'.$request->searchKey.'%');
        }
        if($request->category_id&&$request->category_id!=''){
            $theme=$theme->where('category_id','=',$request->category_id);
        }

        if($request->searchTime&&$request->searchTime!=''){

            $timeArray=explode('~',$request->searchTime);
            $start_time=trim($timeArray[0]);
            $end_time=trim($timeArray[1]);
            $theme=$theme->whereBetween('created_at',[$start_time,$end_time]);
        }
        $theme=$theme->paginate($request->limit)
            ->toArray();

        return $this->page_json_render($theme);
    }
    //创建
    public function create(Request $request){
        return view('admin.theme.edit_add');
    }
    //储存
    public function store(Request $request){
        $name=$request->name;
        $this->filter($request);
        $theme=new Theme();
        $theme->name=$request->name;
        $theme->category_id=$request->category_id;
        $theme->save();
        return redirect()->route('admin.theme_index')->with(
            $this->success()
        );
    }
    //编辑
    public function edit(Request $request,$id){
        $model=Theme::findOrFail($id);
        return view('admin.theme.edit_add',compact('id','model'));
    }
    public function update(Request $request){
        $id=$request->id;
        $this->filter($request);
        $model=Theme::findOrFail($id);
        $model->name=$request->name;
        $model->category_id=$request->cactegory_id;
        $model->save();
        return redirect()->route('admin.theme_index')->with(
            $this->success()
        );
    }
    public function del(Request $request){
        $id=$request->id;
        $model=Theme::findOrFail($id);
        $model->delete();
        return $this->del_success();

    }
    public function delAll(Request $request){

        Theme::whereIn('id',$request->data)->delete();

        return $this->del_success();

    }
    protected function filter($request){
        $this->validate($request,
            [
                'name'=>'required',
                'category_id'=>'required'
            ]);
    }

}
